import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { LoginParamType, LoginService } from '@/services/LoginService'
import {
  LoginUserInfo,
  SystemMenuAncestorsType,
  SystemMenuType,
} from '@/system'
import { COOKIE_TOKEN_KEY } from 'utils/SystemConstants'
import Cookies from 'js-cookie'

/**
 * 将menuArr转换为以数组元素code为key的map结构
 * @param menuArr 非空菜单项数组
 * @param menuMap
 */
function extractMenu(
  menuArr: SystemMenuType[],
  menuMap: Map<string, SystemMenuAncestorsType>,
  parent?: SystemMenuAncestorsType
) {
  menuArr.forEach(item => {
    const menuItem: SystemMenuAncestorsType = { menuItem: item, ancestors: [] }
    if (parent) {
      menuItem.ancestors.push(...parent.ancestors)
      menuItem.ancestors.push(parent)
    }
    menuMap.set(item.code, menuItem)
    if (item.children && item.children.length > 0) {
      extractMenu(item.children, menuMap, menuItem)
    }
  })
}

export const useLoginUserStore = defineStore('LoginUserStore', () => {
  async function doLogin(param: LoginParamType) {
    const loginResult = await LoginService.login(param)
    Cookies.set(COOKIE_TOKEN_KEY, loginResult.token)
  }

  // ----------------------------------------------------------------
  const loginUserInfo = ref<LoginUserInfo | null>(null)
  /**
   * key为菜单code, value为菜单数据的map结构
   */
  const GETTER_MENUS_MAP = computed(() => {
    const menuMap = new Map<string, SystemMenuAncestorsType>()
    if (
      loginUserInfo.value &&
      loginUserInfo.value.menus &&
      loginUserInfo.value.menus.length > 0
    ) {
      extractMenu(loginUserInfo.value.menus, menuMap)
    }
    return menuMap
  })
  function SET_LOGIN_USER_INFO(p: LoginUserInfo) {
    loginUserInfo.value = p
  }
  async function doLoadLoginUserInfo() {
    if (loginUserInfo.value) {
      return
    }
    const loginUserData = await LoginService.loadLoginUserInfo()
    SET_LOGIN_USER_INFO(loginUserData)
  }

  // ----------------------------------------------------------------

  const storeData = { loginUserInfo }
  const GETTERS = { GETTER_MENUS_MAP }
  return {
    ...storeData,
    ...GETTERS,
    doLogin,
    doLoadLoginUserInfo,
  }
})
